// pages/weatherHistory/weatherHistory.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    city: null,
    dateEnd: new Date().getFullYear()+'-'+(new Date().getMonth()+1),
    selectYear: null,
    selectMonth: null,
    activeLine: null,
    activeIndex: null,
    activeDate: null,
    dateList: null,
    weatherList: null
  },

  /**
   * 返回上一页
   */
  pageBack(){
    wx.navigateBack();
  },

  /**
   * 更改查询日期
   */
  changeDate(e){
    var selectValue = e.detail.value.split('-');
    this.setData({
      activeDate: null,
      activeIndex: null,
      activeLine: null,
      dateList: null,
      weatherList: null,
      selectYear: selectValue[0],
      selectMonth: (selectValue[1].length==1?'0':'')+selectValue[1]
    });
    // 获取选择月份历史天气
    this.getHistoryWeather(this.data.city,this.data.selectYear+this.data.selectMonth);
  },

  /**
   * 点击日历天数-展开详情
   */
  clickDay(e){
    var line = e.currentTarget.dataset.line;
    var index = e.target.dataset.index;
    var date = e.target.dataset.date;
    if(!date) return;
    // 点击同一天收起详情
    if(this.data.activeDate==date){
      this.setData({
        activeDate: null,
        activeIndex: null,
        activeLine: null
      });
    }else{
      this.setData({
        activeDate: date,
        activeIndex: index,
        activeLine: line
      });
    }
  },

  /**
   * 获取历史天气
   * @param {String} city 城市名
   * @param {String} date 日期(yyyyMM)
   */
  getHistoryWeather(city,date){
    var areaid;
    if(city=='河南蒙古族自治县'){
      areaid = 101150304;
    }else{
      areaid = '';
    }
    wx.request({
      url: 'https://weather01.market.alicloudapi.com/weatherhistory',
      header:{
        'Authorization': 'APPCODE b0eceff9476841588287706ca6819e6e'
      },
      data:{
        area: city,
        areaid: areaid,
        month: date
      },
      success: res=>{
        var resList = res.data.showapi_res_body.list;
        // 日历列表数组
        var dateList = [];
        if(resList.length>0){
          // 选择的月份第一天星期几(0-6)
          var day = new Date(this.data.selectYear+'-'+this.data.selectMonth).getDay();
          var list;
          if(day>0){
            // 数组前添加day个空字符串
            list = '-'.repeat(day-1).split('-');
          }else{
            list = [];
          }
          // 天气信息对象列表
          var weatherList = {};
          for(var i=0;i<resList.length;i++){
            // 将天气信息日期加入list
            var t = parseInt(resList[i].time.substr(-2));
            if(resList[i-1]){
              var prevT = parseInt(resList[i-1].time.substr(-2));
              // 若日期不连续则补空字符串
              if(t-prevT>1){
                list = list.concat('-'.repeat(t-prevT-2).split('-'));
                console.log(t-prevT)
              }
            }
            list.push(t);
            // 气候对应图片编号
            var weatherName = {
              '晴': '00',
              '多云': '01',
              '阴': '02',
              '阵雨': '03',
              '雷雨': '04',
              '雷阵雨': '04',
              '雷阵雨伴有冰雹': '05',
              '雨夹雪': '06',
              '小雨': '07',
              '中雨': '08',
              '大雨': '09',
              '暴雨': '10',
              '大暴雨': '11',
              '特大暴雨': '12',
              '阵雪': '13',
              '小雪': '14',
              '中雪': '15',
              '大雪': '16',
              '暴雪': '17',
              '雾': '18',
              '冻雨': '19',
              '沙尘暴': '20',
              '小到中雨': '21',
              '中到大雨': '22',
              '大到暴雨': '23',
              '暴雨到大暴雨': '24',
              '大暴雨到特大暴雨': '25',
              '小到中雪': '26',
              '中到大雪': '27',
              '大到暴雪': '28',
              '浮尘': '29',
              '扬沙': '30',
              '强沙尘暴': '31',
              '霾': '53',
              '无': '99',
              '雨': '301',
              '雪': '302'
            };
            var weather = resList[i].weather.split('-');
            var weatherIndex = weather.map(a=>weatherName[a]);
            // 一天内有多个气候则选择靠后的天气展示
            resList[i].weatherIndex = weatherIndex[weatherIndex.length-1];
            // 统一格式-温度不带℃
            resList[i].min_temperature = parseInt(resList[i].min_temperature);
            resList[i].max_temperature = parseInt(resList[i].max_temperature);
            // 以天数作为天气信息对象key
            weatherList[t] = resList[i];
          }
          // 分割数组，7个一行
          for(var i=1;i<=Math.ceil(list.length/7)*7;i++){
            var j = Math.ceil(i/7)-1;
            if(!dateList[j]){
              dateList[j] = [];
            }
            // 最后一行数组后补空字符串
            dateList[j].push((list[i-1]?list[i-1]:''));
          }
        }
        // 更新日历列表以及天气信息
        this.setData({
          dateList: dateList,
          weatherList: weatherList
        });
        console.log(this.data.weatherList,'历史天气信息')
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.city){
      var today = new Date();
      var year = today.getFullYear().toString();
      var month = (today.getMonth()+1).toString();
      this.setData({
        city: options.city,
        selectYear: year,
        selectMonth: (month.length==1?'0':'')+month
      });
      // 获取当前月份历史天气
      this.getHistoryWeather(this.data.city,this.data.selectYear+this.data.selectMonth);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})